import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui


button_value = ["CE", "C", "删除", "÷", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "×", "=", ".", "±", "+"]


class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setAutoFillBackground(True)
        self.setBackgroundRole(QtGui.QPalette.Shadow)
        #算式
        # num_button = MyButton("1")
        self.browser = QtWidgets.QTextBrowser()
        self.browser.setFixedHeight(50)
        self.browser.setFixedWidth(218)
        self.browser.setAlignment(QtCore.Qt.AlignCenter)
        self.browser.setFontPointSize(18)
        # self.browser.setLineWrapMode()
        # 结果
        self.result = QtWidgets.QTextBrowser()
        self.result.setFixedHeight(50)
        self.result.setFixedWidth(218)
        self.result.setAlignment(QtCore.Qt.AlignCenter)
        self.result.setFontPointSize(18)
        self.result.setText('=')
        # 输入
        self.text_edit = QtWidgets.QTextEdit("")
        self.text_edit.setFixedHeight(50)
        self.text_edit.setFixedWidth(218)
        self.text_edit.setFontPointSize(20)
        # self.text_edit.set

        hlayout1 = QtWidgets.QHBoxLayout()
        hlayout1.addWidget(MyButton(button_value[5]))
        hlayout1.addWidget(MyButton(button_value[6]))
        hlayout1.addWidget(MyButton(button_value[7]))
        hlayout1.addWidget(MyButton(button_value[19]))

        hlayout2 = QtWidgets.QHBoxLayout()
        hlayout2.addWidget(MyButton(button_value[8]))
        hlayout2.addWidget(MyButton(button_value[9]))
        hlayout2.addWidget(MyButton(button_value[10]))
        hlayout2.addWidget(MyButton(button_value[14]))

        hlayout3 = QtWidgets.QHBoxLayout()
        hlayout3.addWidget(MyButton(button_value[11]))
        hlayout3.addWidget(MyButton(button_value[12]))
        hlayout3.addWidget(MyButton(button_value[13]))
        hlayout3.addWidget(MyButton(button_value[15]))

        hlayout4 = QtWidgets.QHBoxLayout()
        hlayout4.addWidget(MyButton(button_value[18]))
        hlayout4.addWidget(MyButton(button_value[4]))
        hlayout4.addWidget(MyButton(button_value[17]))
        hlayout4.addWidget(MyButton(button_value[16]))

        hlayout5 = QtWidgets.QHBoxLayout()
        hlayout5.addWidget(MyButton(button_value[0]))
        hlayout5.addWidget(MyButton(button_value[1]))
        hlayout5.addWidget(MyButton(button_value[2]))
        hlayout5.addWidget(MyButton(button_value[3]))

        vlayout = QtWidgets.QVBoxLayout()
        vlayout.addWidget(self.browser)
        vlayout.addWidget(self.result)
        vlayout.addWidget(self.text_edit)
        vlayout.addLayout(hlayout5)
        vlayout.addLayout(hlayout1)
        vlayout.addLayout(hlayout2)
        vlayout.addLayout(hlayout3)
        vlayout.addLayout(hlayout4)
        vlayout.setAlignment(QtCore.Qt.AlignTop)
        # vlayout.setSpacing(1)

        self.setWindowTitle("计算器")
        self.setLayout(vlayout)
        # 计算结果
        self.cresult = 0
        # 1：计算完成，0：未计算
        self.is_rest = 0
        # 上次运算操作符
        self.last_operate = ''
        # self.connect(self.browser, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT("add_brows()"))

    def add_brows(self, operate):
        self.browser.setText(self.browser.toPlainText()+self.text_edit.toPlainText()+operate)

    def get_brows(self):
        return self.browser.toPlainText()

    def clear_brows(self):
        self.browser.setText("")

    def set_result(self, text):
        self.result.setText("="+self.ss(text))

    def clear_result(self):
        self.result.setText("=")

    def get_result(self):
        return self.result.toPlainText()[1:]

    def get_text(self):
        return self.text_edit.toPlainText()

    def append_text(self, text):
        self.text_edit.setText(self.text_edit.toPlainText()+text)

    def clear_text(self):
        self.text_edit.setText("")

    def ss(self, text):
        a = str(text)
        if a.count('.')>0:
            if int(a.split(".")[1]) == 0:
                a = a.split(".")[0]
        return a


def calc_result(my_widget, operate, val):
    if operate == button_value[19]:
        my_widget.cresult += val
    elif operate == button_value[14]:
        my_widget.cresult -= val
    elif operate == button_value[15]:
        my_widget.cresult *= val
    elif operate == button_value[3]:
        my_widget.cresult /= val
    else:
        my_widget.cresult = val

    print(my_widget.cresult)
    # 去掉小数点后面全为0
    # my_widget.result = format(my_widget.result, '.2f')


def is_calc_operate(operate):
    return operate == button_value[19] or operate == button_value[14] or operate == button_value[15] \
           or operate == button_value[3]


class MyButton(QtWidgets.QPushButton):
    def __init__(self, text):
        super().__init__(text)
        # print(self.text())
        # self.text = text
        self.setFixedWidth(50)
        self.setFixedHeight(50)
        # self.event()
        self.connect(self, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT("num_click()"))

    def num_click(self):
        print(self.text().__str__())
        print(type(self.parent()))
        my_widget = self.parent()
        txt = self.text().__str__()
        if is_calc_operate(txt):
            if my_widget.is_rest == 0:
                my_widget.add_brows(txt)
                # oper = my_widget.get_brows().
                calc_result(my_widget, my_widget.last_operate, float(my_widget.get_text()))
                my_widget.last_operate = txt
                my_widget.clear_text()
                my_widget.set_result(my_widget.cresult)
                my_widget.is_rest = 1
        elif txt == button_value[1]:  # C
            my_widget.clear_brows()
            my_widget.clear_text()
            my_widget.clear_result()
            my_widget.result = 0
        elif txt == button_value[0]:  # CE
            my_widget.clear_text()
        elif txt == button_value[2]:  # 删除
            if txt.__len__() > 1:
                my_widget.text_edit.setText(my_widget.get_text()[0:-1])
            else:
                my_widget.text_edit.setText("")
        elif txt == button_value[16]:  # =
            if my_widget.is_rest == 0:
                my_widget.add_brows("")
                calc_result(my_widget, my_widget.last_operate, float(my_widget.get_text()))
                my_widget.text_edit.setText(str(my_widget.result))
                my_widget.is_rest = 1
        elif txt == button_value[17]:
            if my_widget.get_text().find(button_value[17]) == -1:
                my_widget.append_text(txt)
        elif txt == button_value[18]:
            if my_widget.get_text().find("-") == -1:
                my_widget.text_edit.setText("-"+my_widget.get_text());
            else:
                my_widget.text_edit.setText(my_widget.get_text()[1:]);
        else:
            # 刚刚计算过，需恢复为未计算
            if my_widget.is_rest == 1:
                my_widget.is_rest = 0
                my_widget.clear_text()
            my_widget.append_text(txt)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    widget = MyWidget()
    # widget.resize(400, 600)
    widget.show()
    sys.exit(app.exec_())

